package com.jiawa.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiawa.train.business.domain.po.TrainCarriage;
import com.jiawa.train.business.domain.po.TrainSeat;
import com.jiawa.train.business.enums.SeatColEnum;
import com.jiawa.train.business.mapper.TrainCarriageMapper;
import com.jiawa.train.business.mapper.TrainSeatMapper;
import com.jiawa.train.business.req.TrainSeatQueryReq;
import com.jiawa.train.business.req.TrainSeatSaveReq;
import com.jiawa.train.business.resp.TrainSeatQueryResp;
import com.jiawa.train.business.service.ITrainSeatService;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.PageResp;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 座位 服务实现类
 * </p>
 *
 * @author hrz
 * @since 2025-09-07
 */
@Service
@RequiredArgsConstructor
public class TrainSeatServiceImpl extends ServiceImpl<TrainSeatMapper, TrainSeat> implements ITrainSeatService {

    private final TrainCarriageMapper trainCarriageMapper;

    @Override
    public void saveTrainSeat(TrainSeatSaveReq req) {
        //2.判断是新增还是更新
        if(ObjectUtil.isEmpty(req.getId())){
            //新增
            //1.先根据三个字段查询是否重复
            TrainSeat one = this.lambdaQuery()
                    .eq( req.getRow()!=null,TrainSeat::getRow, req.getRow())
                    .eq( req.getCol()!=null,TrainSeat::getCol, req.getCol())
                    .eq(req.getSeatType()!=null,TrainSeat::getSeatType, req.getSeatType())
                    .one();
            if(ObjectUtil.isNotEmpty(one)){
                throw new BusinessException(BusinessExceptionEnum.SEAT_UNIQUE_ERROR);
            }
            TrainSeat trainSeat = BeanUtil.copyProperties(req, TrainSeat.class);
            trainSeat.setCreateTime(LocalDateTime.now());
            trainSeat.setUpdateTime(LocalDateTime.now());
            this.save(trainSeat);
        }else{
            //更新
            TrainSeat trainSeat = this.getById(req.getId());
            BeanUtil.copyProperties(req, trainSeat);
            trainSeat.setUpdateTime(LocalDateTime.now());
            this.updateById(trainSeat);
        }
    }

    @Override
    public PageResp<TrainSeatQueryResp> queryList(TrainSeatQueryReq req) {
        //1.取得车次编号
        String trainCode = req.getTrainCode();
        //2分页查询
        Page<TrainSeat> page = this.lambdaQuery()
                .eq(TrainSeat::getTrainCode, trainCode)
                .orderByAsc(TrainSeat::getCarriageSeatIndex)
                .page(new Page<>(req.getPage(), req.getSize()));
        List<TrainSeat> records = page.getRecords();
        if(ObjectUtil.isEmpty(records)){
            PageResp<TrainSeatQueryResp> objectPageResp = new PageResp<>();
            objectPageResp.setTotal(0L);
            objectPageResp.setList(new ArrayList<>());
            return objectPageResp;
        }
        //3.转VO返回
        List<TrainSeatQueryResp> list = BeanUtil.copyToList(records, TrainSeatQueryResp.class);
        PageResp<TrainSeatQueryResp> objectPageResp = new PageResp<>();
        objectPageResp.setTotal(page.getTotal());
        objectPageResp.setList(list);
        return objectPageResp;
    }
    @Override
    public void delete(Long id) {
        if(ObjectUtil.isEmpty(this.getById(id))){
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        }
        this.removeById(id);
    }

    @Override
    public void genTrainSeat(String trainCode) {
        //1.先清空当前车次下的所有座位记录
        List<Long> ids = this.lambdaQuery()
                .eq(TrainSeat::getTrainCode, trainCode)
                .list().stream().map(TrainSeat::getId).collect(Collectors.toList());
        if(CollUtil.isNotEmpty(ids)){
            baseMapper.deleteBatchIds(ids);
        }
        //2.获取当前车次的所有车厢信息
        List<TrainCarriage> carriageList = trainCarriageMapper
                .selectList(new LambdaQueryWrapper<TrainCarriage>()
                .eq(TrainCarriage::getTrainCode, trainCode));
        //3.遍历车厢信息
        for (TrainCarriage c : carriageList) {
            List<TrainSeat> result = new ArrayList<>();
            //4.获取车厢的座位类型,行数,列数
            String seatType = c.getSeatType();
            Integer rowCount = c.getRowCount();
            List<SeatColEnum> colsByType = SeatColEnum.getColsByType(seatType);
            int seatIndex = 1;
            //5.根据座位类型,行数,列数生成座位   
            for (Integer i = 1; i <= rowCount; i++) {
                for (SeatColEnum seatColEnum : colsByType) {
                    //6.保存到数据库
                    TrainSeat t = new TrainSeat();
                    t.setSeatType(seatColEnum.getType());
                    t.setTrainCode(trainCode);
                    t.setCol(seatColEnum.getCode());
                    t.setRow(StrUtil.fillBefore(i.toString(), '0', 2));
                    t.setCreateTime(LocalDateTime.now());
                    t.setUpdateTime(LocalDateTime.now());
                    t.setCarriageIndex(c.getIndex());
                    t.setCarriageSeatIndex(seatIndex++);
                    result.add(t);
                }
            }
            //7.批量保存
            boolean b = this.saveBatch(result);
        }
    }
}
